<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<head>
    <meta charset="utf-8" />
    <title>Color Admin | Page with Footer</title>
    <meta
            content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
            name="viewport" />
    <meta content="" name="description" />
    <meta content="" name="author" />

    <!-- ================== BEGIN BASE CSS STYLE ================== -->
    <%@ include file="../include/inc_head.jsp"%>
    <!-- ================== END BASE CSS STYLE ================== -->

    <!-- ================== BEGIN BASE JS ================== -->
    <script src="/assets/plugins/pace/pace.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/assets/css/orderStatus.css">
    <!-- ================== END BASE JS ================== -->
</head>
<style>
    .form-horizontal.form-bordered .form-group>.control-label {
        padding: 20px 158px 15px;
        border-right: 1px solid #eee;
        margin-right: -1px;
    }
    .form-horizontal.form-bordered .form-group>div {
        padding: 20px;
        border-left: 1px solid #eee;
    }

    .table>tbody>tr>td, .table>tbody>tr>th, .table>tfoot>tr>td, .table>tfoot>tr>th, .table>thead>tr>td, .table>thead>tr>th {
        padding: 8px;
        line-height: 1.42857143;
        vertical-align: middle;
        border-top: 1px solid #ddd;
    }
</style>
<body>
<!-- begin #page-loader -->
<div id="page-loader" class="fade in">
    <span class="spinner"></span>
</div>
<!-- end #page-loader -->

<!-- begin #page-container -->
<div id="page-container"
     class="fade page-sidebar-fixed page-header-fixed">
    <!-- begin #header -->
    <%@ include file="../include/inc_header.jsp"%>
    <!-- end #header -->

    <!-- begin #sidebar -->
    <%@ include file="../include/inc_left.jsp"%>
    <!-- end #sidebar -->

    <!-- begin #content -->
    <div id="content" class="content">
        <!-- begin breadcrumb -->
        <ol class="breadcrumb pull-right">
            <li><a href="javascript:;">首页</a></li>
            <li class="active">采购单编辑</li>
        </ol>
        <!-- end breadcrumb -->
        <!-- begin page-header -->
        <h1 class="page-header">采购单编辑</h1>
        <button type="button" class="btn btn-primary m-r-5 m-b-5" onclick="back();">返回</button>

        <!-- end page-header -->


        <div class="table-responsive">
            <table id="user" class="table table-bordered table-striped">
                <thead>
                <tr>
                    <td style="width:220px;font-weight:900;font-size: 16px;">采购单信息</td>
                    <td></td>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td style="width:320px;">采购单ID:<a href="#"  style="margin-left: 30px;"><span id="proId"></span></a></td>
                    <td >申请来源:<a href="#" style="margin-left: 30px;"><span id="sourceName"></span></a></td>
                </tr>

                <tr>
                    <td>送货时间:<a href="#" style="margin-left: 30px;"><span id="sDate"></span></a></td>
                    <td style="width:320px;">申请时间:<a href="#" style="margin-left: 30px;" ><span id="eDate"></span></a></td>
                </tr>
                <tr>
                    <td>SKU数量:<a href="#" style="margin-left: 30px;"><span id="skuNum"></span></a></td>
                    <td style="width:320px;">采购总金额:<a href="#" style="margin-left: 30px;" >￥<span id="totalPrice"></span></a></td>
                </tr>
                <tr>
                    <td style="width:320px;" colspan="2">采购状态:<a href="#" style="margin-left: 30px;"><span id="status"></span></a></td>

                </tr>
                </tbody>
            </table>
        </div>
        <div class="panel panel-inverse" data-sortable-id="table-basic-1">
            <div class="panel-heading" style="background: #a5bcd2;">
                <h4 class="panel-title">采购单商品
                </h4>


            </div>
            <div class="panel-body">
                <div class="table-responsive">

                    <table class="table" id="tableItem">
                        <thead>
                        <tr>
                            <th>#</th>

                            <th>SKUID</th>
                            <th>商品名称</th>
                            <th>采购数量</th>
                            <th>采购重量(KG)</th>
                            <th>采购单价（元）</th>
                            <th>采购总价（元）</th>
                            <th><a   href='#'  onclick='addTr2("tableItem",-2)'>新增</a></th>
                        </tr>
                        </thead>
                        <tbody >
                        <c:forEach items="${listData}" var="item" varStatus="list">

                            <tr>
                                <td>${list.index+1}</td>
                                <td>${item.skuCode}</td>
                                <td>${item.skuName}</td>
                                <td> ${item.expectNum/1000} </td>
                                <td> ${item.expectWeight/1000}</td>
                                <td>￥ ${item.unitPrice} </td>
                                <td>￥${item.totalPrice}  </td>
                                <td align="left"><a href='#'  onclick='editRow("${item.procurementItemId}","${item.skuName}","${item.expectNum/1000}",
                                        "${item.expectWeight/1000}","${item.unitPrice}","${item.skuId}")'>修改</a>
                                </td>
                            </tr>
                        </c:forEach>
                        </tr>
                        </tbody>
                        <tfoot>
                        <tr>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th>总计：￥<span id="totalPrices"></span>（元）</th>
                            <th></th>
                        </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>

    </div>
    <!-- end #content -->

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="width:1000px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;
                    </button>
                    <h4 class="modal-title" id="myModalLabel">
                        编辑商品
                    </h4>
                </div>
                <div class="modal-body">
                    <form class="form-inline" action="/purchase/edit" method="POST">
                        <input type="hidden" class="form-control" id="itemId" name="itemId" />
                        <input type="hidden" class="form-control" id="skuId" name="skuId" />
                        <div class="form-group m-r-10">
                            <label class="control-label">商品名称:</label>
                            <input type="text" class="form-control" readonly="readonly" id="skuName" name="skuName" />
                        </div>

                        <div class="form-group m-r-10">
                            <label class="control-label">采购数量:</label>
                            <input type="text" class="form-control" maxlength="10"  id="num" name="num" />
                        </div>
                        <div class="form-group m-r-10">
                            <label class="control-label">采购重量:</label>
                            <input type="text" class="form-control"  id="weight" maxlength="10" name="weight" />
                        </div>
                        <div class="form-group">
                            <label class="control-label">采购价格:</label>
                            <input type="text" class="form-control" id="price" maxlength="10" name="price" />

                        </div>
                       <%-- <div class="form-group">
                            <label class="control-label">采购总价格:</label>
                            <input type="text" class="form-control" id="totalitemPrice" maxlength="10" name="totalitemPrice" />
                        </div>--%>


                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                    </button>
                    <button type="button" id="btnSave" class="btn btn-primary">
                        提交更改
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->

    </div>

    <%@ include file="../include/inc_footer.jsp"%>
    <!-- begin scroll to top btn -->
    <a href="javascript:;"
       class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade"
       data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
    <!-- end scroll to top btn -->
</div>
<!-- end page container -->

<!-- ================== BEGIN BASE JS ================== -->
<%@ include file="../include/inc_foot.jsp"%>

<!-- ================== END BASE JS ================== -->

<!-- ================== BEGIN PAGE LEVEL JS ================== -->
<script src="/assets/plugins/DataTables/media/js/jquery.dataTables.js"></script>
<script src="/assets/plugins/DataTables/media/js/dataTables.bootstrap.min.js"></script>
<script src="/assets/plugins/DataTables/extensions/Responsive/js/dataTables.responsive.min.js"></script>
<script src="/assets/js/table-manage-default.demo.min.js"></script>
<script src="/assets/js/apps.min.js"></script>
<!-- ================== END PAGE LEVEL JS ================== -->

<script>
    $(document).ready(function() {
        App.init();
        TableManageDefault.init();
        initStatus(5);
     //   console.log($.getRequestParameter('id'));
        if($.getRequestParameter('id')!=""){

            $('#proId').html("${procurementOrder.id}");
            $('#sourceName').html("${procurementOrder.applySourceName}");
            $('#status').html("${procurementOrder.statusName}");
            $('#eDate').html("${procurementOrder.applyDateTime}");
            $('#sDate').html("${procurementOrder.deliveryDateTime}");
           // $('#proId').html("${procurementOrder.id}");
            $('#totalPrice').html("${procurementOrder.totalPrice}");
            $('#totalPrices').html("${procurementOrder.totalPrice}");
            $('#skuNum').html("${procurementOrder.skuNum}");
            //$('#proId').html($.getRequestParameter('id'));

            //$('#sourceName').html(decodeURI($.getRequestParameter('applySourceName')));

            //$('#status').html(decodeURI($.getRequestParameter('statusName')));

           // $('#eDate').html($.myTime.UnixToDate($.getRequestParameter('applyDateTime'),true,8));


            //$('#sDate').html($.myTime.UnixToDate($.getRequestParameter('deliveryDateTime'),true,8));

            //$('#totalPrice').html($.getRequestParameter('totalPrice'));

           // $('#totalPrices').html($.getRequestParameter('totalPrice'));
           // $('#skuNum').html($.getRequestParameter('skuNum'));
        }else{
            $('#proId').html(0);
            $('#sourceName').html("B端用户");

            $('#status').html("待入库");

            $('#eDate').html(now);


            $('#sDate').html(now);

            $('#totalPrice').html(0);

            $('#totalPrices').html(0);
            $('#skuNum').html(0);
        }
    });
    function p(s) {
        return s < 10 ? '0' + s: s;
    }

    var myDate = new Date();
    //获取当前年
    var year=myDate.getFullYear();
    //获取当前月
    var month=myDate.getMonth()+1;
    //获取当前日
    var date=myDate.getDate();
    var h=myDate.getHours();       //获取当前小时数(0-23)
    var m=myDate.getMinutes();     //获取当前分钟数(0-59)
    var s=myDate.getSeconds();

    var now=year+'-'+p(month)+"-"+p(date)+" "+p(h)+':'+p(m)+":"+p(s);

    function back(){
        history.go(-1);
    }

    function initStatus(index){
        if(index==-1){
            $('#status-1').show();
            for(var j=0;j<7;j++){
                $('#status'+j).hide();
            }
            return;
        }
        $('#status-1').hide();
        $("#status"+index).attr("class","step-cur");
        if(index>0){
            for(var i=0;i<=index-1;i++){
                $("#status"+i).attr("class","step-done");
            }
            for(var a=index+1;a<=6;a++){
                $("#status"+a).attr("class","ss");
            }
        }else{
            $("#status0"+index).attr("class","step-cur");
            for(var s=1;s<7;s++){
                $("#status"+s).attr("class","ss");
            }
        }
    }


    //修改操作
    function editRow(id,skuname,num,weight,price,skuId) {
      //  console.log(id);
        //alert('You click like action, row: ' + JSON.stringify(row));
        //console.log(row);
        $("#myModal").modal('show');
        $('#itemId').val(id);
        $('#skuName').val(skuname);
        $('#num').val(num);
        $('#weight').val(weight);
        $('#price').val(price);
        $('#skuId').val(skuId);
    }
    $("#btnSave").on("click", function () {

        $.ajax({
            type: 'POST',
            url: "${ctx}/purchase/update/item",
            data: {
                id: $("#itemId").val(),
                expectNum: $("#num").val(),
                expectWeight: $("#weight").val(),
                unitPrice: $("#price").val(),
                skuId: $("#skuId").val()
            },
            success: function (res) {
                window.location.reload();
                $('#myModal').removeClass("hide");

            }
        });
    });


    //修改操作
    function saveRow(obj) {

        var txtSkuId = $(obj).parent().parent().find("td").eq(1).find("input").val();
        var txtSkuName = $(obj).parent().parent().find("td").eq(2).find("input").val();
        var txtNum = $(obj).parent().parent().find("td").eq(3).find("input").val();
        var txtWeight = $(obj).parent().parent().find("td").eq(4).find("input").val();
        var txtPrice = $(obj).parent().parent().find("td").eq(5).find("input").val();
        if(txtSkuId == ""){
            alert("SKUID不能为空");
            return;
        }
        if(txtSkuName == ""){
            alert("商品名称不能为空");
            return;
        }
        if(txtPrice == ""){
            alert("商品单价不能为空");
            return;
        }

       $.ajax({
                type: 'POST',
                url: "${ctx}/purchase/create",
                data: {
                    skuName:txtSkuName,
                    expectNum:txtNum,
                    expectWeight: txtWeight,
                    unitPrice: txtPrice,
                    skuId: txtSkuId
                },
                success: function (res) {
                    window.location.href="${ctx}/purchase/add?id="+res;
                    //window.location.reload();
                   // $('#myModal').removeClass("hide");
                console.log(res);
                }
            });     /**/
    }

</script>

<script>

    $.extend({
        getRequestParameter:function(name){
            //为了调试，把window.location.search 替换为 ?id=123&name=john'
            var url = window.location.search,reg,retVal;
            /*
             * 其中正则详解：
             * (^\?|&)以？或者&开头的字符
             * name是传进来的参数名
             * =([^&]*)(&|$)表示=后面&前面或者到结束的非&的0+个字符
             * 通过()组合方式，并且不把RegExp设置为全局g，可以通过match方法返回匹配到的字符串和pattern数组
             * */
            return name?(reg = new RegExp("(^\\?|&)"+name+"=([^&]*)(&|$)"),retVal = url.match(reg),$.isArray(retVal)&&retVal.length>=3?
                retVal[2]:''):'';
        }
    });
    //修改参数名来进行调试
    //$('#result').html($.getRequestParameter('name'));

    (function($) {
        $.extend({
            myTime: {
                /**
                 * 当前时间戳
                 * @return <int>        unix时间戳(秒)
                 */
                CurTime: function(){
                    return Date.parse(new Date())/1000;
                },
                /**
                 * 日期 转换为 Unix时间戳
                 * @param <string> 2014-01-01 20:20:20  日期格式
                 * @return <int>        unix时间戳(秒)
                 */
                DateToUnix: function(string) {
                    var f = string.split(' ', 2);
                    var d = (f[0] ? f[0] : '').split('-', 3);
                    var t = (f[1] ? f[1] : '').split(':', 3);
                    return (new Date(
                        parseInt(d[0], 10) || null,
                        (parseInt(d[1], 10) || 1) - 1,
                        parseInt(d[2], 10) || null,
                        parseInt(t[0], 10) || null,
                        parseInt(t[1], 10) || null,
                        parseInt(t[2], 10) || null
                    )).getTime() / 1000;
                },
                /**
                 * 时间戳转换日期
                 * @param <int> unixTime    待时间戳(秒)
                 * @param <bool> isFull    返回完整时间(Y-m-d 或者 Y-m-d H:i:s)
                 * @param <int>  timeZone   时区
                 */
                UnixToDate: function(unixTime, isFull, timeZone) {
                    if (typeof (timeZone) == 'number')
                    {
                        unixTime = parseInt(unixTime) + parseInt(timeZone) * 60 * 60;
                    }
                    var time = new Date(unixTime * 1000);
                    var ymdhis = "";
                    ymdhis += time.getUTCFullYear() + "-";
                    ymdhis += (time.getUTCMonth()+1) + "-";
                    ymdhis += time.getUTCDate();
                    if (isFull === true)
                    {
                        ymdhis += " " + time.getUTCHours() + ":";
                        ymdhis += time.getUTCMinutes() + ":";
                        ymdhis += time.getUTCSeconds();
                    }
                    return ymdhis;
                }
            }
        });
    })(jQuery);
</script>

    <script type="text/javascript">
        ////////添加一行、删除一行封装方法///////
        /**
         * 为table指定行添加一行
         *
         * tab 表id
         * row 行数，如：0->第一行 1->第二行 -2->倒数第二行 -1->最后一行
         * trHtml 添加行的html代码
         *
         */
        function addTr(tab, row, trHtml){
            //获取table最后一行 $("#tab tr:last")
            //获取table第一行 $("#tab tr").eq(0)
            //获取table倒数第二行 $("#tab tr").eq(-2)
            var $tr=$("#"+tab+" tr").eq(row);
            if($tr.size()==0){
                alert("指定的table id或行数不存在！");
                return;
            }
            $tr.after(trHtml);
        }

        function delTr(ckb){
            //获取选中的复选框，然后循环遍历删除
            var ckbs=$("input[name="+ckb+"]:checked");
            if(ckbs.size()==0){
                alert("要删除指定行，需选中要删除的行！");
                return;
            }
            ckbs.each(function(){
                $(this).parent().parent().remove();
            });
        }

        /**
         * 全选
         *
         * allCkb 全选复选框的id
         * items 复选框的name
         */
        function allCheck(allCkb, items){
            $("#"+allCkb).click(function(){
                $('[name='+items+']:checkbox').attr("checked", this.checked );
            });
        }

        ////////添加一行、删除一行测试方法///////
        $(function(){
            //全选
            allCheck("allCkb", "ckb");
        });

        function addTr2(tab, row){
            var trHtml="<tr>" +
                " <td>#</td>" +
                " <td><input type='text' style='width:80px;' name='txtSkuCode' maxlength='6'></td>" +
                " <td><input type='text' style='width:120px;' name='txtSkuName' maxlength='20'></td>" +
                " <td> <input type='text' style='width:80px;' name='txtNum' maxlength='10'> </td>" +
                " <td> <input type='text' style='width:80px;' name='txtWeight' maxlength='10'></td>" +
                " <td>￥ <input type='text' style='width:80px;' name='txtPrice' maxlength='10'></td>" +
                " <td>￥</td>" +
                " <td align=left><a href='#'  onclick=saveRow(this)>保存</a> &nbsp;&nbsp;&nbsp;&nbsp;<a href='#'  onclick=delTr2(this)>删除</a> " +
                " </td>" +
                " </tr>";
            addTr(tab, row, trHtml);
        }

        function delTr2(obj){
                $(obj).parent().parent().remove();
        }
    </script>
</body>
</html>


